//
//  SearchTableViewController.m
//  CloudKaraoke
//
//  Created by BHDMinh on 4/28/14.
//  Copyright (c) 2014 soncamedia. All rights reserved.
//

#import "SearchTableViewController.h"

@interface SearchTableViewController ()
{
    // Search Background Queue
    NSInteger taskCounter;
    dispatch_queue_t backgroundQueue;
}
@end

@implementation SearchTableViewController
//@synthesize cmpareBlock, completion;
@synthesize allData;
@synthesize displayData;
@synthesize loadingIndicator;
@synthesize searchBar;
@synthesize tableViewData;

#pragma mark - SearchBar and SearchDisplayController
- (void) searchBarButtonItemDidPresses
{
    [searchBar setHidden:NO];
    [searchBar becomeFirstResponder];
}

#pragma mark - searchDisplayController
- (void) customizeSearchBar
{
    // Search Bar Customization
    UISearchBar *aSearchBar = searchBar; //[self.searchDisplayController searchBar];
    if (!aSearchBar) return;
    
    [aSearchBar setShowsCancelButton:YES];
    
    UIBarButtonItem *cancelButton = nil;
    
    UIView *barSubView = nil;
    if(SYSTEM_VERSION_GREATER_THAN(@"7.0")) {
        barSubView = aSearchBar.subviews[0];
    }else {
        barSubView = aSearchBar;
    }
    
    if (!barSubView) {
        return;
    }
    
    for (UIView *subview in barSubView.subviews)
    {
        if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
        {
            [subview removeFromSuperview];
        } else if ([subview isKindOfClass:NSClassFromString(@"UINavigationButton")]){
            cancelButton = (UIBarButtonItem *)subview;
        }
    }
    [aSearchBar setBackgroundColor:KOK_COLOR_NAV_BAR];
    
    if(cancelButton) {
        [(UIButton *) cancelButton setTitle:@"Huỷ" forState:UIControlStateNormal];
    }
    
    cancelButton = [UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil];
    if (cancelButton) {
        [cancelButton setTintColor:[UIColor whiteColor]];
        [cancelButton setBackgroundImage:[[UIImage alloc] init] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
        [cancelButton setBackgroundImage:[[UIImage alloc] init] forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
        
        NSDictionary *attributes =
        [NSDictionary dictionaryWithObjectsAndKeys:
         KOK_COLOR_AUTHOR, UITextAttributeTextColor,
         [UIColor colorWithRed:0 green:0 blue:0 alpha:0.0], UITextAttributeTextShadowColor,
         [NSValue valueWithUIOffset:UIOffsetMake(0, 0)], UITextAttributeTextShadowOffset,
         [UIFont systemFontOfSize:14.0], UITextAttributeFont,
         nil];
        
        [cancelButton setTitleTextAttributes:attributes forState:UIControlStateNormal];
        [cancelButton setTitleTextAttributes:attributes forState:UIControlStateHighlighted];
    }
}

#pragma mark - SearchDisplayController
- (void) searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
    float offset = 0;
    if (!SYSTEM_VERSION_LESS_THAN(@"7.0")) {
        offset = 20;
    }
    [self customizeSearchBar];
    searchActive = TRUE;
    [controller.searchBar setFrame:CGRectMake(0, offset, searchBar.frame.size.width, searchBar.frame.size.height)];
    
    offset = 0;
    if (!SYSTEM_VERSION_LESS_THAN(@"7.0")) {
        offset = 44;
    }
    [tableViewData setFrame:CGRectMake(0, offset, tableViewData.frame.size.width, self.view.frame.size.height - searchBar.frame.size.height)];
    
    if (allData != nil && [allData count] > 0) {
        [tableViewData scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

- (void) searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
    float offset = 0;
    if (!SYSTEM_VERSION_LESS_THAN(@"7.0")) {
        if(!IS_IPAD && UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation]))
        {
            offset = 52;
        }else {
            offset = 64;
        }
    }
    [controller.searchBar setFrame:CGRectMake(0, offset, searchBar.frame.size.width, searchBar.frame.size.height)];
    [controller.searchBar setHidden:YES];
    
    [tableViewData setFrame:CGRectMake(0, 0, tableViewData.frame.size.width, self.view.frame.size.height)];
    searchActive = NO;
    
    searchString = @"";
    [tableViewData reloadData];
}

- (void)searchDisplayController:(UISearchDisplayController *)controller didHideSearchResultsTableView:(UITableView *)tableView {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide) name:UIKeyboardWillHideNotification object:nil];
}

- (void) keyboardWillHide {
    
    UITableView *tableView = [[self searchDisplayController] searchResultsTableView];
    [tableView setContentInset:UIEdgeInsetsZero];
    [tableView setScrollIndicatorInsets:UIEdgeInsetsZero];
}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchText
{
    if(![searchString isEqualToString:searchText])
    {
        searchString = searchText;
        [self handleSearch:searchString completeBlock:^{
            [controller.searchResultsTableView reloadData];
        }];
    }
    return NO;
}

- (id) DataForTableView:(UITableView *)tableView
{
    if([tableView isEqual:self.searchDisplayController.searchResultsTableView]) {
        return displayData;
    }
    return allData;
}

/*
#pragma mark - UISearchBarDelegate
- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar1
{
    [searchBar1 resignFirstResponder];
}

- (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar1
{
    searchString = @"";
    [searchBar1 resignFirstResponder];
    
    [self handleSearch:searchString completeBlock:^{
        [self.searchDisplayController.searchResultsTableView reloadData];
        if ([displayData count] > 0) {
//            [self.tableViewData scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }
    }];
}

- (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if(![searchString isEqualToString:searchText])
    {
        searchString = searchText;
        [self handleSearch:searchString completeBlock:^{
            // [self.tableViewData reloadData];
            [self.searchDisplayController.searchResultsTableView reloadData];
        }];
    }
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar1
{
    [searchBar1 setShowsCancelButton:YES animated:YES];
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar1
{
    [searchBar1 setShowsCancelButton:NO animated:YES];
    return YES;
}
*/

#pragma mark - SearchEngineHandle
- (void) handleSearch:(NSString *) searchText completeBlock:(completeBlock)completion{
    taskCounter++;
    dispatch_async(backgroundQueue, ^(void) {
        if(taskCounter > 1)
        {
            taskCounter--;
            return;
        }
        
        if(displayData) {
            [displayData removeAllObjects];
        } else {
            displayData = [[NSMutableArray alloc] init];
        }
        
        dispatch_sync(dispatch_get_main_queue(), ^(void) {
            if (completion) {
                completion();
            }
        });
        
        if(searchText == nil || searchText.length == 0)
        {
//            dispatch_async(dispatch_get_main_queue(), ^(void) {
//                if (completion) {
//                    completion();
//                }
                taskCounter--;
//            });
            return;
        }
        
        NSInteger lastPinyin = 0;
        for (id obj in allData) {
            if( _compareBlock){
                SCCompareResult result = _compareBlock(obj,searchText);
                if (result == SCComparePinyin) {
                    [displayData insertObject:obj atIndex:lastPinyin++];
                }else if(result == SCCompareName || result == SCCompareTitleRaw) {
                    [displayData addObject:obj];
                }
            }
            if (taskCounter > 1) {
                taskCounter--;
                return;
            }
        }
        
        dispatch_sync(dispatch_get_main_queue(), ^(void) {
            if (completion) {
                completion();
            }
            taskCounter--;
        });
    });
}

#pragma mark - ViewInitialize and Memory Management
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if(self.searchDisplayController) {
        [self.searchDisplayController setDelegate:self];
    }
    
    backgroundQueue = dispatch_queue_create("com.sonca.cloudkaraoke.searchengine", NULL);
    
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(uigestureRecognizerHandler:)];
    [panGesture setDelegate:self];
    [self.view addGestureRecognizer:panGesture];
    
    searchString = @"";
    [searchBar setHidden:YES];
    [self customizeSearchBar];
    [searchBar setShowsCancelButton:NO];
    [searchBar setPlaceholder:@"Tìm kiếm"];
}

#pragma mark -
#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]]) {
        // pan gesture is attached to a custom view
        return YES;
    }
    
    return NO;
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    return YES;
}

- (BOOL) gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    if(searchActive) return NO;
    return YES;
}

- (void) uigestureRecognizerHandler:(UIPanGestureRecognizer *)recognizer
{
    CGPoint translatedPoint = [recognizer translationInView:self.view];
    if (translatedPoint.y < 0) {
        if([searchBar isHidden]) {
            float offset = 0;
            if (!SYSTEM_VERSION_LESS_THAN(@"7.0")) {
                if(!IS_IPAD && UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation]))
                {
                    offset = 52;
                }else {
                    offset = 64;
                }
            }
            [searchBar setFrame:CGRectMake(0, offset, searchBar.frame.size.width, searchBar.frame.size.height)];
            [searchBar setHidden:NO];
        }
    }else if (translatedPoint.y > 0)
    {
        if(![searchBar isHidden]){
            [searchBar setHidden:YES];
        }
    }
    
    
//    if([sender isKindOfClass:[UISwipeGestureRecognizer class]]) {
//        UISwipeGestureRecognizer *swipeGesture = (UISwipeGestureRecognizer *)sender;
//        if (swipeGesture.direction == UISwipeGestureRecognizerDirectionDown) {
//            if(![searchBar isHidden]){
//                [searchBar setHidden:YES];
//            }
//        }else if(swipeGesture.direction == UISwipeGestureRecognizerDirectionUp) {
//            if([searchBar isHidden]) {
//                [searchBar setHidden:NO];
//            }
//        }
//    }
}

- (void) dealloc
{
}

@end
